const express = require('express')
// const crypto = require('crypto')
const validate = require('express-validation')
// const _ = require('lodash')
// const moment = require('moment')
const goodController = require('../controller/goodController')
const translationController = require('../controller/translationController')
const tokenChecker = require('../util/tokenChecker')

const goodRouter = express.Router()
const countPerPage = 30

goodRouter.get('/getGoods', tokenChecker, async (req, res, next) => {
  // 分页，每页30个商品
  const page = parseInt(req.query.page, 10) || ''
  try {
    const goods = await goodController.getGoods({
      shopId: '',
      page,
      countPerPage
    })
    res.json({
      status: 200,
      msg: '获取商品成功',
      data: {
        goods
      }
    })
  } catch (e) {
    next(e)
  }
})

goodRouter.get('/pageCount', tokenChecker, async (req, res, next) => {
  // 分页，每页30个商品
  try {
    const count = await goodController.count()
    const pageCount = Math.ceil(count / countPerPage)
    res.json({
      status: 200,
      msg: '商品数量',
      data: {
        pageCount
      }
    })
  } catch (e) {
    next(e)
  }
})

goodRouter.post('/saveTranslation', tokenChecker, async (req, res, next) => {
  const { translation } = req.body
  try {
    const result = await translationController.saveTranslation(translation)
    res.json({
      status: 200,
      msg: '保存翻译成功',
      data: {}
    })
  } catch (e) {
    next(e)
  }
})
goodRouter.post('/add', tokenChecker, async (req, res, next) => {
  const { goods } = req.body
  try {
    const targetShopId = req.uuId
    _.forEach(goods, (item) => {
      item.shopId = targetShopId
    })
    const result = await goodController.createGoods(goods)
    res.json({
      status: 200,
      msg: '保存商品成功',
      data: {
        goods: result
      }
    })
  } catch (e) {
    next(e)
  }
})

goodRouter.post('/upsert', tokenChecker, async (req, res, next) => {
  // 每次只能添加或更新一个商品
  const { good } = req.body
  try {
    const targetShopId = req.uuId
    good.shopId = targetShopId
    // await goodController.createGoods(goods)
    const result = await goodController.upsertGood(good)
    if (!result) {
      res.json({
        status: 200,
        msg: '更新商品成功',
        data: {}
      })
      return
    }
    res.json({
      status: 200,
      msg: '添加商品成功',
      data: {}
    })
  } catch (e) {
    next(e)
  }
})

goodRouter.post('/delete', tokenChecker, async (req, res, next) => {
  // 每次只能添加或更新一个商品
  // [{id:''}]
  const { goods } = req.body
  try {
    const result = await goodController.delete(goods)
    // if (!result) {
    //   res.json({ status: 200, msg: '保存商品成功', data: {} })
    // }
    res.json({
      status: 200,
      msg: '删除商品成功',
      data: {}
    })
  } catch (e) {
    next(e)
  }
})

module.exports = goodRouter
